import { ref } from 'vue'
import { defineStore } from 'pinia'
import apiClient from '../services/api'

// 定义学习数据类型
export interface LearningData {
  id: string
  userQuery: string
  assistantResponse: string
  correctedResponse: string
  feedback: string
  isPositive: boolean
  createdAt: string
  usedInTraining: boolean
}

// 定义训练任务类型
export interface TrainingTask {
  id: string
  name: string
  status: 'pending' | 'running' | 'completed' | 'failed'
  startTime: string
  endTime: string | null
  progress: number
  datasetSize: number
  adapterName: string
  logs: string[]
}

// 定义LoRA适配器类型
export interface LoRAAdapter {
  id: string
  name: string
  description: string
  createdAt: string
  size: number
  isActive: boolean
  metrics: {
    accuracy: number
    loss: number
    trainingTime: number
  }
}

// 学习管理store
export const useLearningStore = defineStore('learning', () => {
  // 状态
  const learningData = ref<LearningData[]>([])
  const trainingTasks = ref<TrainingTask[]>([])
  const loraAdapters = ref<LoRAAdapter[]>([])
  const selectedTrainingTask = ref<TrainingTask | null>(null)
  const isLoading = ref<boolean>(false)
  const isTraining = ref<boolean>(false)
  const searchKeyword = ref<string>('')
  const filters = ref({
    usedInTraining: null as boolean | null,
    dateRange: null as [string, string] | null
  })
  const pagination = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0
  })

  // 加载学习数据
  const loadLearningData = async () => {
    isLoading.value = true
    try {
      // 调用API获取学习数据
      const response = await apiClient.get('/v1/learning/data', {
        params: {
          page: pagination.value.currentPage,
          pageSize: pagination.value.pageSize,
          searchKeyword: searchKeyword.value,
          ...filters.value
        }
      })
      learningData.value = response.data.items || []
      pagination.value.total = response.data.total
    } catch (error) {
      console.error('加载学习数据失败:', error)
    } finally {
      isLoading.value = false
    }
  }



  // 加载训练任务
  const loadTrainingTasks = async () => {
    isLoading.value = true
    try {
      // 调用API获取训练任务
      const response = await apiClient.get('/v1/learning/tasks')
      trainingTasks.value = response.data.tasks || []
    } catch (error) {
      console.error('加载训练任务失败:', error)
    } finally {
      isLoading.value = false
    }
  }



  // 加载LoRA适配器
  const loadLoRAAdapters = async () => {
    isLoading.value = true
    try {
      // 调用API获取LoRA适配器
      const response = await apiClient.get('/v1/learning/lora-adapters')
      loraAdapters.value = response.data.adapters || []
    } catch (error) {
      console.error('加载LoRA适配器失败:', error)
    } finally {
      isLoading.value = false
    }
  }



  // 提交学习反馈
  const submitLearningFeedback = async (
    userQuery: string,
    assistantResponse: string,
    correctedResponse: string,
    feedback: string,
    isPositive: boolean
  ) => {
    try {
      // 调用API提交学习反馈
      const response = await apiClient.post('/v1/learning/feedback', {
        user_query: userQuery,
        assistant_response: assistantResponse,
        corrected_response: correctedResponse,
        feedback: feedback,
        is_positive: isPositive
      })
      
      if (response.data.success) {
        // 重新加载学习数据
        await loadLearningData()
        return true
      }
      return false
    } catch (error) {
      console.error('提交学习反馈失败:', error)
      return false
    }
  }

  // 开始训练周期
  const startTrainingCycle = async (maxSamples: number = 1000, adapterName?: string) => {
    if (isTraining.value) {
      return false
    }
    
    isTraining.value = true
    
    try {
      // 调用API开始训练周期
      const response = await apiClient.post('/v1/learning/train', {
        max_samples: maxSamples,
        adapter_name: adapterName
      })
      
      if (response.data.success) {
        // 重新加载训练任务和LoRA适配器
        await loadTrainingTasks()
        await loadLoRAAdapters()
        return true
      }
      return false
    } catch (error) {
      console.error('开始训练周期失败:', error)
      return false
    } finally {
      isTraining.value = false
    }
  }

  // 热加载LoRA适配器
  const hotReloadLoRAAdapter = async (adapterName: string) => {
    try {
      // 调用API热加载LoRA适配器
      const response = await apiClient.post('/v1/learning/lora-adapters/reload', {
        adapter_name: adapterName
      })
      
      if (response.data.success) {
        // 更新适配器状态
        loraAdapters.value.forEach(adapter => {
          adapter.isActive = adapter.name === adapterName
        })
        return true
      }
      return false
    } catch (error) {
      console.error('热加载LoRA适配器失败:', error)
      return false
    }
  }

  // 搜索学习数据
  const searchLearningData = async (keyword: string) => {
    searchKeyword.value = keyword
    pagination.value.currentPage = 1
    await loadLearningData()
  }

  // 清空搜索
  const clearSearch = async () => {
    searchKeyword.value = ''
    pagination.value.currentPage = 1
    await loadLearningData()
  }

  // 设置过滤器
  const setFilters = async (newFilters: Partial<typeof filters.value>) => {
    filters.value = { ...filters.value, ...newFilters }
    pagination.value.currentPage = 1
    await loadLearningData()
  }

  // 清空过滤器
  const clearFilters = async () => {
    filters.value = {
      usedInTraining: null,
      dateRange: null
    }
    pagination.value.currentPage = 1
    await loadLearningData()
  }

  // 查看训练任务详情
  const viewTrainingTaskDetails = (taskId: string) => {
    selectedTrainingTask.value = trainingTasks.value.find(task => task.id === taskId) || null
  }

  // 关闭训练任务详情
  const closeTrainingTaskDetails = () => {
    selectedTrainingTask.value = null
  }

  return {
    // 状态
    learningData,
    trainingTasks,
    loraAdapters,
    selectedTrainingTask,
    isLoading,
    isTraining,
    searchKeyword,
    filters,
    pagination,
    // 方法
    loadLearningData,
    loadTrainingTasks,
    loadLoRAAdapters,
    submitLearningFeedback,
    startTrainingCycle,
    hotReloadLoRAAdapter,
    searchLearningData,
    clearSearch,
    setFilters,
    clearFilters,
    viewTrainingTaskDetails,
    closeTrainingTaskDetails
  }
})